var do_App = sm("do_App");
var do_Page = sm("do_Page");
var nf = sm("do_Notification");
var hashdata = mm("do_HashData");
var deviceone = require("deviceone");
var circleUrl = require("url/circle");
var qqHttp = require("helper/http");
var listdata = mm("do_ListData");

// UI
var headerAout = ui("headerAout");
var aLayoutRoot = ui("aLayoutRoot");
var listView=ui("listView");

// 加载头部
var addheader = headerAout.add("header", "source://view/reuse/header.ui", 0, 0);
// andriod返回键
do_Page.on("back", function() {
	do_App.closePage();
});
// 左上角-返回
var headerLeft = ui(addheader + ".headerLeft");
// 右上角-
var headerRight = ui(addheader + ".headerRight");
var labelNext = ui(addheader + ".labelNext");
labelNext.visible = true;
headerLeft.on("touch", function() {
	do_App.closePage()
});
var header = ui("header");

header.bindData(hashdata);
hashdata.addData({
	"labelTitle" : "圈子",
	"labelNext" : "确认"
})
header.refreshData();
var bizzId;
var forWhat = null;//选择一个圈子的下一步是为了做什么【addCircleTopic:发布圈子话题;addCircleVote:发布圈子投票】
var httpURL = circleUrl.url.base.myCircles;
//页面装载完成后，开始初始化工作
do_Page.on("loaded", function(data) {
	var data=do_Page.getData();
	bizzId=data.bizzId;
	forWhat = data.forWhat;
	if(forWhat == "addCircleTopic"){
		httpURL = circleUrl.url.base.myOrderlyCircles; //发布动态时选择圈子时【最近发布过话题的圈子排在前面】
	}else if(forWhat == "addCircleActivity"){//发布活动时只能选择我管理的圈子【创建的+管理的】
		httpURL = circleUrl.url.base.myManageCircles;
	}
	laodData();
});
listView.bindItems(listdata);
//刷新数据

function laodData() {
	qqHttp.post(httpURL, {}, function(data) {
		listView.rebound();
		listdata.removeAll();
		if(data.circleList.length){
			listdata.addData(data.circleList);
			if(null!=bizzId&&''!=bizzId){
				for (var i = 0; i < listdata.getCount(); i++) {
					var d = listdata.getOne(i);
					if (d.id==bizzId){
						d.source = "source://image/common/radiocheck.png";
						listdata.updateOne(i, d);
						break;
					}
				}
			}
		}
		else{
			listdata.addData(noData);
		}
		listView.refreshItems();
	})
}

// 下拉列表，刷新数据
listView.on("pull", function(data) {
	if (data.state == 2) {
		laodData();
	}
});

// 上拉列表，翻页数据
listView.on("push", function(data) {
	if (data.state == 2) {
		listView.rebound();
	}
});

var name,id;
listView.on("touch", function(index) {
	for (var i = 0; i < listdata.getCount(); i++) {
		var d = listdata.getOne(i);
		if (index == i){
			name=d.name;
			id=d.id;
			d.source = "source://image/common/radiocheck.png";
		}else{
			d.source = "source://image/common/radio.png";
		}
		listdata.updateOne(i, d);
	}
	listView.refreshItems();
});

headerRight.on("touch", function() {
	if(null==id||''==id){
		nf.toast("请选择一个圈子。");
		return;
	}
	do_App.closePage({"type":"circle","name":name,"id":id,"action":"selectOneCircleBack","forWhat":forWhat})
})
